package wifiunion.com.notice.fragment;

import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.NoticeUserAdapter;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.entity.NoticeUserList;
import wifiunion.com.notice.presenter.GetNotificationUserPresenter;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.AddSubInputView;
import wifiunion.com.notice.widget.LoadMoreFooterView;
import wifiunion.com.notice.widget.selectmemberdialog.SelectMemberDialog;

/**
 * Created by Administrator on 2016/11/28.
 * 添加识别对象
 */

public class AddRecognitionTargetFragment extends BaseFragment implements OnLoadMoreListener, OnRefreshListener, NoticeContact.View, View.OnClickListener {

    private View mMainView;

    private LoadMoreFooterView mLoadMoreFooterView;
    private IRecyclerView mRecyclerView;
    private int pageNum = 1;
    private int pageSize = 10;
    private EditText searchEt;

    private NoticeUserAdapter mAdapter;

    //分组成员
    private TextView addSBDXTv;


    private GetNotificationUserPresenter mGetNotificationUserPresenter;
    private ArrayList<NoticeUserList> noticeUserList = new ArrayList<NoticeUserList>();

    private LinearLayout mGroupLayout, mListHeaderLayout;

    //当前通知的UUid
    private String noticeUuid;

    private int mType = 0;

//    private AddNoticeUserDialog mAddNoticeUserDialog;

    private SelectMemberDialog selectMemberDialog;

    private TextView headDowntv;
    private TextView headUpTv;
    private int pageType;

    private ImageView ovalsbdxIv;
    private TextView titlesbdxTv;

    private TextView groupDelTv;

    private Button searchBtn;

    private LinearLayout filterLayout2;

    private NoticeInfoList mNoticeInfoList;

    private RelativeLayout guideRl;

    private RelativeLayout dataRl;

    private RelativeLayout bottonRl;

    private CheckBox mTempCb;

    private AddSubInputView mSubView, mAddView;

    private android.support.constraint.Group mIcongroup;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addrecognitiontarget, container, false);
        mGetNotificationUserPresenter = new GetNotificationUserPresenter(getContext(), this);
        Bundle bundle = getArguments();
        if (null != bundle) {
            pageType = bundle.getInt("pageType");
            if (pageType == 1 || pageType == 2) {
                mNoticeInfoList = (NoticeInfoList) bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();
            }
        }

        initview();

        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initData();

    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void initview() {

        ovalsbdxIv = (ImageView) mMainView.findViewById(R.id.oval_sbdx_iv);
        ovalsbdxIv.setBackgroundResource(R.drawable.notice_mark_material_select);
        titlesbdxTv = (TextView) mMainView.findViewById(R.id.title_sbdx_tv);

        guideRl = (RelativeLayout) mMainView.findViewById(R.id.notice_guide_rl);
        dataRl = (RelativeLayout) mMainView.findViewById(R.id.notice_data_rl);

        if (pageType == 0) {
            boolean isguide = SharedPreferencesUtils.getBooleanSharedPreferences(
                    "noticeguide", getActivity());
            if (!isguide) {
                guideRl.setVisibility(View.VISIBLE);
                dataRl.setVisibility(View.GONE);
            } else {
                guideRl.setVisibility(View.GONE);
                dataRl.setVisibility(View.VISIBLE);
            }
        }


        bottonRl = (RelativeLayout) mMainView.findViewById(R.id.botton_rl);
        bottonRl.setOnClickListener(this);

        mListHeaderLayout = (LinearLayout) mMainView.findViewById(R.id.list_noticelistheader);
        mRecyclerView = (IRecyclerView) mMainView.findViewById(R.id.notice_irecyclerView);
        addSBDXTv = (TextView) mMainView.findViewById(R.id.group_add_tv);
        addSBDXTv.setText("添加识别对象");
        addSBDXTv.setVisibility(View.VISIBLE);
        addSBDXTv.setOnClickListener(this);
        if (pageType == 0 || pageType == 2) {
            addSBDXTv.setEnabled(true);
        } else {
            addSBDXTv.setEnabled(false);
        }

        filterLayout2 = (LinearLayout) mMainView.findViewById(R.id.sub_header_filter_layout2);
        filterLayout2.setVisibility(View.GONE);

        groupDelTv = (TextView) mMainView.findViewById(R.id.group_del_tv);
        groupDelTv.setVisibility(View.GONE);

        searchBtn = (Button) mMainView.findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(this);
        searchBtn.setVisibility(View.GONE);


        headDowntv = (TextView) mMainView.findViewById(R.id.notice_head_down_tv);
        headDowntv.setOnClickListener(this);
        headUpTv = (TextView) mMainView.findViewById(R.id.notice_head_up_tv);
        headUpTv.setVisibility(View.GONE);


        searchEt = (EditText) mMainView.findViewById(R.id.search_edt);
        searchEt.setHint("");
        searchEt.setVisibility(View.GONE);

        mLoadMoreFooterView = (LoadMoreFooterView) mRecyclerView.getLoadMoreFooterView();

        mRecyclerView.setOnLoadMoreListener(this);
        mRecyclerView.setOnRefreshListener(this);

        refreshView(mType);
        mMainView.findViewById(R.id.back).setOnClickListener(this);


        mTempCb = mMainView.findViewById(R.id.temp_cb);
        mAddView = mMainView.findViewById(R.id.max_temp_view);
        mSubView = mMainView.findViewById(R.id.min_temp_view);

        mIcongroup = mMainView.findViewById(R.id.icon_group);
        mTempCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mIcongroup.setVisibility(View.VISIBLE);
                    mTempCb.setSelected(true);
                } else {
                    mIcongroup.setVisibility(View.GONE);
                    mTempCb.setSelected(false);
                }

            }
        });
    }

    public void initData() {
        noticeUserList.clear();
        if (!TextUtils.isEmpty(noticeUuid)) {
//            getSbdxListRequest();
            mRecyclerView.setRefreshing(true);

        }

    }


    @Override
    public void onLoadMore() {

        if (!TextUtils.isEmpty(noticeUuid)) {
            pageNum += 1;
            getSbdxListRequest();
            mRecyclerView.setRefreshing(true);

        }

    }

    @Override
    public void onRefresh() {

        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        noticeUserList.clear();
        mAdapter.notifyDataSetChanged();
        pageNum = 1;
        if (!TextUtils.isEmpty(noticeUuid)) {
            getSbdxListRequest();
            mRecyclerView.setRefreshing(true);
        }

    }


    public void getSbdxListRequest() {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("pageNum", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(pageSize));

        if (null != searchEt.getText().toString() && searchEt.getText().toString().length() > 0) {
            params.put("condition", searchEt.getText().toString());
        }
        if (!TextUtils.isEmpty(noticeUuid)) {
            params.put("uuid", noticeUuid);
        }

        mGetNotificationUserPresenter.getNotificationUser(params);
    }

    @Override
    public void onProgress() {

    }

    @Override
    public void onError(Object obj) {

    }

    @Override
    public void onSuccess(Object obj) {

    }

    @Override
    public void getGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeListSuccess(Object obj) {

    }

    //获取识别对象返回成功
    @Override
    public void getNotificationUserSuccess(Object obj) {

        ArrayList<NoticeUserList> list = (ArrayList<NoticeUserList>) obj;
        if (null != list && list.size() > 0) {
            noticeUserList.addAll(list);
        }
        if (null != getActivity()) {
            mAdapter.notifyDataSetChanged();
            mRecyclerView.setRefreshing(false);
            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        }
    }

    @Override
    public void getNotificationRelGroupList(Object obj) {

    }

    @Override
    public void getNoticeRelGroupMemberListSuccess(Object obj) {

    }

    @Override
    public void addNoticeSBDXSuccess(String noticeUuid) {

    }

    @Override
    public void addSBSDSuccess(Object obj) {

    }


    @Override
    public void onGetDeviceLocListSuccess(Object obj) {

    }

    @Override
    public void onGetDeviceListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeDeviceSuccess(Object obj) {

    }

    @Override
    public void getTopGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeTargetListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetRelGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeTarGetDeviceSuccess(Object obj) {

    }

    @Override
    public void addNoticeDataSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeSuccess(Object obj) {

    }

    @Override
    public void addNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void addNoticeRelGroupSuccess(Object obj) {

    }

    @Override
    public void setNoticeFromSuccess(Object obj) {

    }

    @Override
    public void getNoticeDetailSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeGroupSuccess(Object obj) {

    }

    private void refreshView(int type) {

        mAdapter = new NoticeUserAdapter(getActivity(), type, noticeUserList);
        mListHeaderLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mRecyclerView.setIAdapter(mAdapter);
    }


    @Override
    public void setPresenter(BasePresenter tp) {

    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.group_add_tv) {
            if (noticeUuid == null) {
                noticeUuid = "0";
            }

//            mAddNoticeUserDialog = new AddNoticeUserDialog(getContext(), getActivity(), noticeUuid, myListener, 0, -2);
//            mAddNoticeUserDialog.setTitleMsg("添加识别对象");
//            mAddNoticeUserDialog.show();
//            mAddNoticeUserDialog.setCancelable(false);


            selectMemberDialog = SelectMemberDialog.newInstance(noticeUuid, -2, 0);
            selectMemberDialog.setCallback(myListener);

            if (mTempCb.isChecked()) {
                if(TextUtils.isEmpty(mSubView.getCurrentValue())||TextUtils.isEmpty(mAddView.getCurrentValue()))
                {
                 //donothing
                }
                else{
                    try {
                        String subStr = mSubView.getCurrentValue();
                        String addStr = mAddView.getCurrentValue();
                        if(Float.parseFloat(subStr)<Float.parseFloat(addStr)){
                            selectMemberDialog.setTempParam(mSubView.getCurrentValue(), mAddView.getCurrentValue());
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }

            selectMemberDialog.show(getFragmentManager(), "");


        } else if (i == R.id.notice_head_down_tv) {
            if (null != noticeUuid && !"0".equals(noticeUuid)) {

                if (pageType == 1) {
                    AddRecognitionIntervalFragment aif = new AddRecognitionIntervalFragment();
                    Bundle bundle = new Bundle();
                    if (pageType != 0) {
                        bundle.putSerializable("notice", mNoticeInfoList);
                    } else {
                        bundle.putString("noticeUuid", noticeUuid);
                    }
                    bundle.putInt("pageType", pageType);
                    aif.setArguments(bundle);

                    getFragmentManager().beginTransaction().replace(R.id.reight_fl, aif, "43").addToBackStack(null).commit();
                } else {
                    if (!noticeUserList.isEmpty()) {
                        AddRecognitionIntervalFragment aif = new AddRecognitionIntervalFragment();
                        Bundle bundle = new Bundle();
                        if (pageType != 0) {
                            bundle.putSerializable("notice", mNoticeInfoList);
                        } else {
                            bundle.putString("noticeUuid", noticeUuid);
                        }
                        bundle.putInt("pageType", pageType);
                        aif.setArguments(bundle);

                        getFragmentManager().beginTransaction().replace(R.id.reight_fl, aif, "43").addToBackStack(null).commit();
                    } else {
                        Toast.makeText(getContext(), "请先添加识别对象", Toast.LENGTH_SHORT).show();
                    }
                }

            } else {
                Toast.makeText(getContext(), "请先添加识别对象", Toast.LENGTH_SHORT).show();
            }

//            case R.id.search_btn:
//
//                if(!TextUtils.isEmpty(noticeUuid))
//                {
//                    getSbdxListRequest();
//                    mRecyclerView.setRefreshing(true);
//
//                }
//
//
//
//                break;
        } else if (i == R.id.botton_rl) {
            SharedPreferencesUtils.setBooleanSharedPreferences(
                    "noticeguide", true, getActivity());

            guideRl.setVisibility(View.GONE);
            dataRl.setVisibility(View.VISIBLE);


        } else if (i == R.id.back) {
            getFragmentManager().popBackStack();

        }

    }

    private MyNoticeListener myListener = new MyNoticeListener() {
        @Override
        public void refreshData(final String text) {

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

//                    mAddNoticeUserDialog.dismiss();
                    //设置通知Id
                    noticeUuid = text;

                    noticeUserList.clear();
                    mAdapter.notifyDataSetChanged();
                    pageNum = 1;
                    if (!TextUtils.isEmpty(text)) {
                        getSbdxListRequest();
                    }


                }
            });

        }

        @Override
        public void refreshCancelData(final String text) {


        }

        @Override
        public void onResponse(List<Object> data) {

        }

    };


}








